/**
 * lg_iphone Script by Giraldo Rosales.
 * Visit www.liquidgear.net for documentation and updates.
 *
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/
function LGInit(e) {
	lg.bind('touchmove', function(e) {
		if(!lg.pref.scroll) {
			e.preventDefault();
		}
	});
	
	lg.info.update();
	lg.trigger('lg_init');
}

/** LG iPhone Library **/
var lg = {
	queue:[],
	active:false,
	development:true,
	ui:null,
	
	accelerometer:{
		x:0,
		y:0,
		z:0,
		active:false,
		
		start:function(update) {
			if(!update) {
				update = 1/40;
			}
			var obj	= {};
			obj.activate	= true;
			obj.update		= update;
			lg.addCall('lg://accelerometer?'+lg.json.encode(obj));
			lg.accelerometer.active = true;
		},
		stop:function() {
			var obj	= {};
			obj.activate	= false;
			lg.addCall('lg://accelerometer?'+lg.json.encode(obj));
			lg.accelerometer.active = false;
		},
		
		callback:function(data) {
			lg.accelerometer.x	= data.x;
			lg.accelerometer.y	= data.y;
			lg.accelerometer.z	= data.z;
			lg.trigger('lg_accelerometer');
			return true;
		}
	},
	
	admob:{
		hide:function() {
			var obj		= {};
			obj.action	= 'hide';
			lg.addCall('lg://admob?'+lg.json.encode(obj));
		},
		
		show:function(pos) {
			if(!pos) pos = 'top';
			
			var obj			= {};
			obj.action		= 'show';
			obj.position	= pos;
			lg.addCall('lg://admob?'+lg.json.encode(obj));
		}
	},
	
	audio:{
		play:function(str) {
			var obj 	= {};
			obj.file	= str;
			lg.addCall('lg://sound?'+lg.json.encode(obj));
		}
	},
	
	call:function(phone) {
		lg.addCall('tel:'+phone);
	},
	
	contacts:{
		list:[],
		
		all:function() {
			lg.addCall('lg://contacts');
		},
		
		firstName:function(str) {
			var obj	= {};
			obj.category	= "firstName";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		nickName:function(str) {
			var obj	= {};
			obj.category	= "nickName";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		lastName:function(str) {
			var obj	= {};
			obj.category	= "lastName";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		email:function(str) {
			var obj	= {};
			obj.category	= "email";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		phone:function(str) {
			var obj	= {};
			obj.category	= "phone";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		org:function(str) {
			var obj	= {};
			obj.category	= "org";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		dept:function(str) {
			var obj	= {};
			obj.category	= "dept";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		title:function(str) {
			var obj	= {};
			obj.category	= "title";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		search:function(str) {
			var obj	= {};
			obj.category	= "search";
			obj.value		= str;
			lg.addCall('lg://contacts?'+lg.json.encode(obj));
		},
		
		callback:function(data) {
			lg.contacts.list = data.contacts;
			lg.trigger('lg_contacts');
			return true;
		}
	},
	
	database:{
		db:null,
		results:[],
		
		open:function(obj) {
			obj.action	= 'open';
			if(!obj.type) obj.type = 'local';
			lg.database.db	= null;
			
			if(obj.type == 'local') {
				if (window.openDatabase) {
					lg.database.db = openDatabase(obj.name, '1.0', 'LG_db', 2500000);
				}
			} else {
				lg.addCall('lg://database?'+lg.json.encode(obj));
			}
		},
		
		execute:function(str) {
			var obj		= {};
			obj.action	= 'execute';
			var fStr	= str;
			fStr		= fStr.replace(/\"/g, '""');
			fStr		= fStr.replace(/\'/g, "''");
			obj.query	= fStr;
			
			if(lg.database.db) {
				lg.database.db.transaction(
					function(transaction) {
						transaction.executeSql(str);
					}
				);
			} else {
				lg.addCall('lg://database?'+lg.json.encode(obj));
			}
		},
		
		query:function(str) {
			var obj		= {};
			obj.action	= 'query';
			str			= str.replace(/\"/g, '""');
			str			= str.replace(/\'/g, "''");
			obj.query	= str;
			
			if(lg.database.db) {
				lg.database.db.transaction(
					function(transaction) {
						transaction.executeSql(str, null, lg.database.response, lg.database.error);
					}
				);
			} else {
				lg.addCall('lg://database?'+lg.json.encode(obj));
			}
		},
		
		callback:function(data) {
			lg.database.results = data.results;
			lg.trigger('lg_database');
			return true;
		},
		
		response:function(transaction, results) {
			lg.database.results	= [];
			
			for(var g=0; g<results.rows.length; g++) {
				var row = results.rows.item(g);
				lg.database.results.push(row);
			}
			
			lg.trigger('lg_database');
			return true;
		},
		
		error:function(transaction, error) {
			lg.database.results = [];
			lg.trigger('lg_database_error');
			return true;
		}
	},
	
	email:{
		send:function(obj) {
			obj.action	= 'send';
			lg.addCall('lg://email?'+lg.json.encode(obj));
		}
	},
	
	image:{
		file:{},
		error:{},
		
		camera:function(obj) {
			if(!obj) {
				obj	= {};
			}
			
			obj.type	= "camera";
			lg.addCall('lg://image?'+lg.json.encode(obj));
		},
		
		library:function(obj) {
			if(!obj) {
				obj	= {};
			}
			
			obj.type	= "library";
			lg.addCall('lg://image?'+lg.json.encode(obj));
		},
		
		web:function(obj) {
			if(!obj) {
				obj	= {};
			}
			
			obj.type	= "web";
			lg.addCall('lg://image?'+lg.json.encode(obj));
		},
		
		callback:function(data) {
			if(data.file) {
				lg.image.file	= data.file;
			}
			else if(data.error) {
				lg.image.error	= data.error;
			}
			
			if(data.type == 'camera') {
				lg.trigger('lg_image_camera');
			}
			else if(data.type == 'library') {
				lg.trigger('lg_image_library');
			}
			else if(data.type == 'web') {
				lg.trigger('lg_image_web');
			}
			
			return true;
		}
	},
	
	info:{
		appVersion:'',
		batteryLevel:null,
		batteryState:null,
		height:460,
		id:null,
		lgVersion:null,
		model:null,
		name:null,
		os:null,
		proximity:null,
		version:null,
		width:320,
		wifi:false,
		
		update:function() {
			lg.addCall('lg://info');
		},
		
		callback:function(data) {
			if(data.appVersion) lg.info.appVersion = data.appVersion;
			if(data.batteryLevel) lg.info.batteryLevel = data.batteryLevel;
			if(data.batteryState) lg.info.batteryState = data.batteryState;
			if(data.id) lg.info.id = data.id;
			if(data.lgVersion) lg.info.lgVersion = data.lgVersion;
			if(data.model) lg.info.model = data.model;
			if(data.name) lg.info.name = data.name;
			if(data.os)	lg.info.os = data.os;
			if(data.proximity) lg.info.proximity = data.proximity;
			if(data.version) lg.info.version = data.version;
			if(data.wifi) lg.info.wifi = data.wifi;
			
			//Resize stage
			if(data.width && data.height) {
				var orgW	= lg.info.width;
				var orgH	= lg.info.height;
				
				if(data.width) lg.info.width	= parseFloat(data.width);
				if(data.height) lg.info.height	= parseFloat(data.height);
				
				if(data.width != orgW || data.height != orgH) {
					lg.trigger('lg_resize');
				}
			}
			
			lg.trigger('lg_info');
			return true;
		}
	},
	
	location:{
		accuracy:0,
		latitude:0,
		longitude:0,
		altitude:0,
		speed:0,
		direction:0,
		watchID:null,
		error:{},
		
		start:function(obj){
			if(!obj) {
				obj	= {};
				obj.accuracy	= 3;
			}
			
			var options				= {};
			options.highAccuracy	= (obj.accuracy >=3) ? true : false;
			
			if(obj.timeout) {
				options.timeout		= obj.timeout;
			}
			
			if(obj.maximumAge) {
				options.maximumAge	= obj.maximumAge;
			}
			
			obj.activate		= true;
			lg.addCall('lg://location?'+lg.json.encode(obj));
		},
		
		stop:function(){
			var obj	= {};
			obj.activate	= false;
			
			if(lg.info.version >= 3) {
				navigator.geolocation.clearWatch(lg.location.watchID);
			} else {
				lg.addCall('lg://location?'+lg.json.encode(obj));
			}
		},
		
		getLocation:function(){
			//navigator.geolocation.getCurrentPosition(lg.location.callback, lg.location.error);
			
		},
		
		callback:function(data) {
			if(data.error) {
				lg.location.error	= data.error;
			} else {
				lg.location.latitude	= data.coords.latitude;
				lg.location.longitude	= data.coords.longitude;
				lg.location.altitude	= data.coords.altitude;
				lg.location.accuracy	= data.coords.accuracy;
				lg.location.accuracy	= data.coords.altitudeAccuracy;
				lg.location.speed		= data.coords.speed;
				lg.location.direction	= data.coords.heading;
			}
			
			lg.trigger('lg_location');
		},
		
		error:function(error) {
			lg.location.error	= error;
			lg.trigger('lg_location_error');
		}
	},
	
	maps:{
		directions:function(obj) {
			lg.addCall('http://maps.google.com?saddr='+obj.from+'&daddr='+obj.to);
		},
		
		pinpoint:function() {
			lg.maps.point(lg.location.latitude,lg.location.longitude);
		},
		
		point:function(obj) {
			lg.addCall('http://maps.google.com?ll='+obj.latitude+','+obj.longitude);
		},
		
		search:function(str) {
			if(lg.location.latitude != 0 && lg.location.longitude != 0) {
				lg.addCall('http://maps.google.com?q='+str+'&sll='+lg.location.latitude+','+lg.location.longitude);
			} else {
				lg.addCall('http://maps.google.com?q='+str);
			}
		}
	},
	
	navigation:{
		active:false,
		autoOpen:true,
		list:[],
		error:{},
		
		add:function(obj) {
			lg.navigation.list.push(obj);
			obj.action	= 'add';
			lg.addCall('lg://navigation?'+lg.json.encode(obj));
		},
		
		callback:function(data) {
			if(data.back) {
				lg.trigger('lg_navigation_back');
			} else {
				lg.trigger('lg_navigation');
			}
		},
		
		hide:function() {
			var obj		= {};
			obj.action	= 'hide';
			lg.addCall('lg://navigation?'+lg.json.encode(obj));
			lg.navigation.active	= false;
		},
		
		next:function(id) {
			if(id.indexOf('page_') < 0) {
				id	= 'page_'+id;
			}
			
			//Find page in list
			var page	= lg.page.getByID(id);
			
			//Add Page to NavBar
			if(page && page.navigation) {
				lg.navigation.add(page);
			}
			
			//Set current positions
			lg.page.previous	= lg.page.current;
			lg.page.current		= id;
			lg.page.next		= null;
			
			if(lg.navigation.list.length > 1) {
				//Slide Pages
				lg.page.slideIn(lg.page.current);
				
				if(page.callback) {
					window.setTimeout(page.callback+'();', 0.1);
				}
				
				if(lg.page.previous) {
					lg.page.slideLeft(lg.page.previous);
				}
			}
		},
		
		previous:function() {
			//Slide Pages
			lg.page.slideRight(lg.page.next);
			
			if(lg.page.current) {
				lg.page.slideIn(lg.page.current);
			}
		},
		
		remove:function(id) {
			if(id.indexOf('page_') < 0) {
				id	= 'page_'+id;
			}
			
			var itemLen	= lg.navigation.list.length;
			
			for(g=0; g<itemLen; g++) {
				var obj	= lg.navigation.list[g];
				
				if(obj.id == id) {
					lg.navigation.list.splice(g);
					break;
				}
			}
		},
		
		show:function(obj) {
			obj.action	= 'show';
			lg.addCall('lg://navigation?'+lg.json.encode(obj));
			lg.navigation.active	= true;
		}
	},
	
	notify:{
		sfxBeep:'beep.mp3',
		
		alert:function(obj) {
			lg.addCall('lg://notifyAlert?'+lg.json.encode(obj));
		},
		
		badge:function(num) {
			var obj 	= {};
			obj.label	= num;
			lg.addCall('lg://notifyBadge?'+lg.json.encode(obj));
		},
		
		beep:function() {
			var obj 	= {};
			obj.file	= lg.notify.sfxBeep;
			lg.addCall('lg://sound?'+lg.json.encode(obj));
		},
		
		vibrate:function(time) {
			var obj 	= {};
			obj.time	= time;
			lg.addCall('lg://notifyVibrate?'+lg.json.encode(obj));
		}
	},
	
	pref:{
		scroll:true
	},
	
	session:{
		getValue:function(str) {
			window.localStorage.getItem(str);
		},
		setValue:function(str, val) {
			window.localStorage.setItem(str, val);
		},
		remove:function(str) {
			window.localStorage.removeItem(str);
		}
	},
	
	sms:function(phone) {
		lg.addCall('sms:'+phone);
	},
	
	tabs:{
		active:false,
		
		add:function(obj) {
			obj.action	= 'add';
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		badge:function(btnNum, value) {
			var obj		= {};
			obj.action	= 'badge';
			obj.btn		= btnNum;
			obj.value	= value;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		hide:function() {
			var obj			= {};
			obj.action		= 'hide';
			lg.tabs.active	= false;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		remove:function(id) {
			var obj		= {};
			obj.action	= 'remove';
			obj.btn		= id;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		select:function(btnNum) {
			var obj		= {};
			obj.action	= 'select';
			obj.btn		= btnNum;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		show:function() {
			var obj			= {};
			obj.action		= 'show';
			lg.tabs.active	= true;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		},
		
		unselect:function() {
			var obj		= {};
			obj.action	= 'select';
			obj.btn		= 0;
			lg.addCall('lg://tabs?'+lg.json.encode(obj));
		}
	},
	
	touch:{
		callback:function(data) {
			if(data.event) {
				lg.trigger(data.event);
			}
		}
	},
	
	throbber:{
		active:false,
		
		show:function() {
			if(!lg.throbber.active) {
				lg.throbber.active	= true;
				
				var obj		= {};
				obj.action	= 'show';
				lg.addCall('lg://throbber?'+lg.json.encode(obj));
			}
		},
		
		hide:function() {
			if(lg.throbber.active) {
				lg.throbber.active	= false;
				
				var obj		= {};
				obj.action	= 'hide';
				lg.addCall('lg://throbber?'+lg.json.encode(obj));
			}
		}
	},
	
	video:{
		goto: function() {
			lg.addCall('lg://video');
		}
	},
	
	youtube:{
		play:function(obj) {
			lg.addCall('lg://youtube?'+lg.json.encode(obj));
		}
	},
	
	/** Private Methods **/
	addCall:function(call) {
		lg.queue.push(call);
		
		if(!lg.active) {
			lg.nextCall();
		}
	},
	
	bind:function(name, callback) {
		document.addEventListener(name, callback, false);
	},
	
	nextCall:function() {
		if(lg.queue.length > 0) {
			lg.active	= true;
			var next	= lg.queue.shift();
			
			if(!lg.development) {
				document.location = next;
				//window.setTimeout("document.location = '" + next + "';", 0.1);
			} else {
				lg.nextCall();
			}
		} else {
			lg.active = false;
		}
	},
	
	loadTimer:null, 
	onLoad:function(fn) {
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
			lg.development	= false;
		}
		
		if (/WebKit/i.test(navigator.userAgent)) {
			lg.loadTimer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(lg.loadTimer);
					window.setTimeout(fn+'();', 0.1);
				}
			}, 10);
		}
	},
	
	trigger:function(name) {
		var evt	= document.createEvent('Events');
		evt.initEvent(name, true, true);
		document.dispatchEvent(evt);
		
		return evt;
	}
};
//Load after page is loaded
lg.onLoad('LGInit');
/*
lg.dom	= {
	get:function(id) {
		return document.getElementById(id);
	},
	is:function(el, nodeType) {
		if(el.nodeType == 1){
			if(el.tagName.toLowerCase() == nodeType.toLowerCase()){
				return true;
			}
		}
		return false;
	}
};
*/
lg.json = {
    encode:function(value, replacer, space) {
		var i;
		gap = '';
		var indent = '';
		
		if (typeof space === 'number') {
			for (i = 0; i < space; i += 1) {
				indent += ' ';
			}
			
		} else if (typeof space === 'string') {
			indent = space;
		}
		
		rep = replacer;
		if (replacer && typeof replacer !== 'function' &&
				(typeof replacer !== 'object' ||
				 typeof replacer.length !== 'number')) {
			throw new Error('JSON.encode');
		}
		
		return this.str('', {'': value});
    },
    
    decode:function(text, reviver) {
		var j;
		var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
		
		function walk(holder, key) {
			var k, v, value = holder[key];
			
			if (value && typeof value === 'object') {
				for (k in value) {
					if (Object.hasOwnProperty.call(value, k)) {
						v = walk(value, k);
						if (v !== undefined) {
							value[k] = v;
						} else {
							delete value[k];
						}
					}
				}
			}
			return reviver.call(holder, key, value);
		}
		
		cx.lastIndex = 0;
		
		if (cx.test(text)) {
			text = text.replace(cx, function (a) {
				return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
			});
		}
		
		if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
			j = eval('(' + text + ')');
			return typeof reviver === 'function' ? walk({'': j}, '') : j;
		}
		
		throw new SyntaxError('JSON.parse');
	},
	
    f:function(n) {
        return n < 10 ? '0' + n : n;
    },
	
	DateToJSON:function(key) {
		return this.getUTCFullYear() + '-' + this.f(this.getUTCMonth() + 1) + '-' + this.f(this.getUTCDate())      + 'T' + this.f(this.getUTCHours())     + ':' + this.f(this.getUTCMinutes())   + ':' + this.f(this.getUTCSeconds())   + 'Z';
	},
	
	StringToJSON:function(key) {
		return this.valueOf();
    },
    
    quote:function(string) {
        var meta = {'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};
        var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    },
    
    str:function(key, holder) {
        var indent='', gap = '', i, k, v, length, mind = gap, partial, value = holder[key];
        
        if (value && typeof value === 'object') {
            switch((typeof value)) {
            	case 'date':
            		this.DateToJSON(key);
            		break;
            	default:
            		this.StringToJSON(key);
            		break;
            }
        }
        
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        	case 'string':
        	    return this.quote(value);
			case 'number':
	            return isFinite(value) ? String(value) : 'null';
			case 'boolean':
			case 'null':
	            return String(value);
	        case 'object':
				if (!value) {
					return 'null';
				}
				gap += indent;
				partial = [];
				
				if (Object.prototype.toString.apply(value) === '[object Array]') {
					length = value.length;
					
					for (i = 0; i < length; i += 1) {
						partial[i] = this.str(i, value) || 'null';
					}
	
					v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
					gap = mind;
					return v;
				}
					
				if (rep && typeof rep === 'object') {
					length = rep.length;
					for (i = 0; i < length; i += 1) {
						k = rep[i];
						if (typeof k === 'string') {
							v = this.str(k, value);
							if (v) {
								partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				} else {
					for (k in value) {
						if (Object.hasOwnProperty.call(value, k)) {
							v = this.str(k, value);
							if (v) {
								partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				}

				v = partial.length === 0 ? '{}' :
					gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
							mind + '}' : '{' + partial.join(',') + '}';
				gap = mind;
				return v;
		}
	}
};